using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.IO;
using System.Web.SessionState;
using NetWing.Model;
using NetWing.Bll;
using Omu.ValueInjecter;
using NetWing.BPM.Core;
using NetWing.BPM.Core.Bll;
using NetWing.Common;
using NetWing.Common.Data;
using NetWing.Common.Data.SqlServer;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using NetWing.Common.Excel;
using NetWing.Common.IO;
using NetWing.Common.IO.DirFile;
using NetWing.Common.Data.Filter;
using NetWing.BPM.Core.Model;
using NetWing.BPM.Core.Dal;

namespace NetWing.BPM.Admin.MJWbtc.ashx
{
    /// <summary>
    /// 外部停车 的摘要说明
    /// </summary>
    public class MJWbtcHandler : IHttpHandler, IRequiresSessionState
    {
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            int k;
            var json = HttpContext.Current.Request["json"];
            var rpm = new RequestParamModel<MJWbtcModel>(context) { CurrentContext = context };
            if (!string.IsNullOrEmpty(json))
            {
                rpm = JSONhelper.ConvertToObject<RequestParamModel<MJWbtcModel>>(json);
                rpm.CurrentContext = context;
            }

            switch (rpm.Action)
            {
                case "add"://添加时事务方法处理财务
                    int wbtckeyid = 0;//外部停车keyid
                    int mainInsertedId = 0;//（主表公用）主表插入的ID
                    string edNumber = common.mjcommon.getedNumber("TC");//得到此次财务订单号，原来是浏览器给，现在从系统获取

                    MJWbtcModel a = new MJWbtcModel();
                    a.InjectFrom(rpm.Entity);
                    a.depid = SysVisitor.Instance.UserDepId;
                    a.ownner = SysVisitor.Instance.UserId;
                    a.firsttime = a.order_endtime;
                    a.edNumber = edNumber;//初始停车时单号
                    
                    #region 财务主表处理
                    MJFinanceMainModel mainModel = new MJFinanceMainModel();//初始化模型
                    mainModel.add_time = DateTime.Now;
                    mainModel.up_time = DateTime.Now;
                    mainModel.edNumber = edNumber;
                    mainModel.depid = int.Parse(SysVisitor.Instance.cookiesUserDepId);//数据权限部门ID
                    mainModel.dep = SysVisitor.Instance.cookiesCurrentDepName;
                    mainModel.ownner = int.Parse(SysVisitor.Instance.cookiesUserId);//数据所有者ID
                    mainModel.unit = a.connman;//联系人
                    mainModel.unitid = 0;//应为不在用户系统里面故此填写0
                    mainModel.contact = SysVisitor.Instance.cookiesUserName;
                    mainModel.contactid = int.Parse(SysVisitor.Instance.cookiesUserId);//经手人
                    mainModel.depid = a.depid;//部门权限
                    mainModel.ownner = a.ownner;//个人所有者权限
                    //mainModel.note = a.connman + "外部停车收据";这一样留到下面处理
                    mainModel.account = a.account;
                    mainModel.accountid = a.accountid;//因为数据处理
                    mainModel.accountidb = a.accountid;
                    mainModel.accountb = a.account;
                    mainModel.shifub = a.tcf + a.lanya_money + a.menjin_money;//三个费用加起来
                    mainModel.total = mainModel.shifub;
                    mainModel.payment = mainModel.shifub;
                    mainModel.operate = SysVisitor.Instance.cookiesUserName;
                    mainModel.operateid = int.Parse(SysVisitor.Instance.cookiesUserDepId);
                    #endregion


                    #region 数据库事务
                    SqlTransaction tran = SqlHelper.BeginTransaction(SqlEasy.connString);//取得一个事务
                    try
                    {

                        //先写外部停车主表返回KeyId
                        wbtckeyid = DbUtils.tranInsert(a, tran);
                        //再写财务主表返回财务主表keyid
                        mainModel.note = a.connman + "外部停车收据，外部停车表ID是："+wbtckeyid;
                        mainInsertedId = DbUtils.tranInsert(mainModel, tran);


                        #region 财务明细表处理-停车费
                        //先处理费用科目以便以后更新和系统一致
                        DataRow fdr = SqlEasy.ExecuteDataRow("select * from MJaccountingSubjects where keyid="+a.subjectid+"");


                        MJFinanceDetailModel detailModeltcf = new MJFinanceDetailModel();//初始化明细表模型
                        detailModeltcf.edNumber = edNumber;//订单号赋值
                        detailModeltcf.financeId = mainInsertedId;//父子表关联
                        detailModeltcf.add_time = DateTime.Now;
                        detailModeltcf.up_time = DateTime.Now;
                        detailModeltcf.ownner = int.Parse(SysVisitor.Instance.cookiesUserId);//数据所有者ID
                        detailModeltcf.depid = int.Parse(SysVisitor.Instance.cookiesUserDepId);//数据权限部门ID
                        detailModeltcf.ftype = "收入";
                        detailModeltcf.subject = fdr["subjectName"].ToString();
                        detailModeltcf.subjectid = int.Parse(fdr["keyid"].ToString());
                        detailModeltcf.num = 1;
                        detailModeltcf.sprice = a.tcf;//停车费
                        detailModeltcf.sumMoney = a.tcf;
                        detailModeltcf.stime = a.order_starttime;
                        detailModeltcf.etime = a.order_endtime;
                        detailModeltcf.note = a.connman + "停车费(外部)"+a.carNo;
                        detailModeltcf.username = a.connman;
                        detailModeltcf.mobile = a.mobile;
                        detailModeltcf.contact = SysVisitor.Instance.cookiesUserName;
                        detailModeltcf.contactid = int.Parse(SysVisitor.Instance.cookiesUserId);
                        //detailModeltcf.carno = a.carNo;//车牌或车架号 废弃不用
                        

                        #endregion


                        #region 财务明细表处理-蓝牙卡押金
                        //先处理费用科目以便以后更新和系统一致
                        DataRow ldr = SqlEasy.ExecuteDataRow("select * from MJaccountingSubjects where keyid=36");


                        MJFinanceDetailModel detailModelly = new MJFinanceDetailModel();//初始化明细表模型
                        detailModelly.edNumber = edNumber;//订单号赋值
                        detailModelly.financeId = mainInsertedId;//父子表关联
                        detailModelly.add_time = DateTime.Now;
                        detailModelly.up_time = DateTime.Now;
                        detailModelly.ownner = int.Parse(SysVisitor.Instance.cookiesUserId);//数据所有者ID
                        detailModelly.depid = int.Parse(SysVisitor.Instance.cookiesUserDepId);//数据权限部门ID


                        detailModelly.ftype = "收入";
                        detailModelly.subject = ldr["subjectName"].ToString();
                        detailModelly.subjectid = int.Parse(ldr["keyid"].ToString());
                        detailModelly.num = 1;
                        detailModelly.sprice = a.lanya_money;//蓝牙卡押金
                        detailModelly.sumMoney = a.lanya_money;
                        detailModelly.stime = a.order_starttime;
                        detailModelly.etime = a.order_endtime;
                        detailModelly.note = a.connman + "蓝牙卡押金(外部)";
                        detailModelly.username = a.connman;
                        detailModelly.mobile = a.mobile;
                        detailModelly.contact = SysVisitor.Instance.cookiesUserName;
                        detailModelly.contactid = int.Parse(SysVisitor.Instance.cookiesUserId);


                        #endregion

                        #region 财务明细表处理-门禁卡押金
                        //先处理费用科目以便以后更新和系统一致
                        DataRow mdr = SqlEasy.ExecuteDataRow("select * from MJaccountingSubjects where keyid=6");


                        MJFinanceDetailModel detailModelmj = new MJFinanceDetailModel();//初始化明细表模型
                        detailModelmj.edNumber = edNumber;//订单号赋值
                        detailModelmj.financeId = mainInsertedId;//父子表关联
                        detailModelmj.add_time = DateTime.Now;
                        detailModelmj.up_time = DateTime.Now;
                        detailModelmj.ownner = int.Parse(SysVisitor.Instance.cookiesUserId);//数据所有者ID
                        detailModelmj.depid = int.Parse(SysVisitor.Instance.cookiesUserDepId);//数据权限部门ID

                        detailModelmj.ftype = "收入";
                        detailModelmj.subject = mdr["subjectName"].ToString();
                        detailModelmj.subjectid = int.Parse(mdr["keyid"].ToString());
                        detailModelmj.num = 1;
                        detailModelmj.sprice = a.menjin_money;//门禁卡押金
                        detailModelmj.sumMoney = a.menjin_money;
                        detailModelmj.stime = a.order_starttime;
                        detailModelmj.etime = a.order_endtime;
                        detailModelmj.note = a.connman + "门禁卡押金(外部)";
                        detailModelmj.username = a.connman;
                        detailModelmj.mobile = a.mobile;
                        detailModelmj.contact = SysVisitor.Instance.cookiesUserName;
                        detailModelmj.contactid = int.Parse(SysVisitor.Instance.cookiesUserId);


                        #endregion

                        //以上先处理逻辑
                        //更新三个明细表
                        DbUtils.tranInsert(detailModeltcf, tran);//停车费
                        DbUtils.tranInsert(detailModelly, tran);//蓝牙卡
                        DbUtils.tranInsert(detailModelmj, tran);//门禁卡
                        tran.Commit();//提交执行事务
                        #region 写成功日志
                        LogModel log = new LogModel();
                        log.BusinessName = "临时停车办理成功";
                        log.OperationIp = PublicMethod.GetClientIP();
                        log.OperationTime = DateTime.Now;
                        log.PrimaryKey = "";
                        log.UserId = int.Parse(SysVisitor.Instance.cookiesUserId);
                        log.TableName = "";
                        log.note = "零时停车业务办理成功";
                        log.OperationType = (int)OperationType.Other;
                        LogDal.Instance.Insert(log);
                        #endregion

                        context.Response.Write("{\"status\":1,\"msg\":\"提交成功！\"}");
                    }
                    catch (Exception e)
                    {
                        LogModel log = new LogModel();
                        log.BusinessName = "外部停车办理失败";
                        log.OperationIp = PublicMethod.GetClientIP();
                        log.OperationTime = DateTime.Now;
                        log.PrimaryKey = "";
                        log.UserId = int.Parse(SysVisitor.Instance.cookiesUserId);
                        log.TableName = "";
                        log.note = e.Message.ToString();
                        log.OperationType = (int)OperationType.Other;
                        LogDal.Instance.Insert(log);


                        tran.Rollback();//错误！事务回滚！
                        context.Response.Write("{\"status\":0,\"msg\":\"" + e.ToString() + "\"}");
                        throw;
                    }
                    #endregion

                    //context.Response.Write(MJWbtcBll.Instance.Add(a));
                    //context.Response.Write(MJWbtcBll.Instance.Add(rpm.Entity));
                    break;



                case "tyj":
                    int tyjmainInsertedId = 0;//（主表公用）主表插入的ID
                    //tctf 停车退费
                    string tuiedNumber = common.mjcommon.getedNumber("TT");//得到此次财务订单号，原来是浏览器给，现在从系统获取
                    MJWbtcModel tyj = new MJWbtcModel();
                    tyj.InjectFrom(rpm.Entity);
                    tyj.KeyId = rpm.KeyId;
                    tyj.tuiedNumber = tuiedNumber;//最后一次续费单号
                    tyj.lastxftime = DateTime.Now;
                    tyj.lanya_money = -tyj.lanya_money;//因为是退费所以变为-
                    tyj.menjin_money = -tyj.menjin_money;

                    SqlTransaction tyjtran = SqlHelper.BeginTransaction(SqlEasy.connString);//取得一个事务
                    try
                    {


                        #region 财务主表处理
                        MJFinanceMainModel tyjmainModel = new MJFinanceMainModel();//初始化模型
                        tyjmainModel.add_time = DateTime.Now;
                        tyjmainModel.up_time = DateTime.Now;
                        tyjmainModel.edNumber = tuiedNumber;
                        tyjmainModel.depid = int.Parse(SysVisitor.Instance.cookiesUserDepId);//数据权限部门ID
                        tyjmainModel.dep = SysVisitor.Instance.cookiesCurrentDepName;
                        tyjmainModel.ownner = int.Parse(SysVisitor.Instance.cookiesUserId);//数据所有者ID
                        tyjmainModel.unit = tyj.connman;//联系人
                        tyjmainModel.unitid = 0;//应为不在用户系统里面故此填写0
                        tyjmainModel.contact = SysVisitor.Instance.cookiesUserName;
                        tyjmainModel.contactid = int.Parse(SysVisitor.Instance.cookiesUserId);//经手人
                        tyjmainModel.depid = tyj.depid;//部门权限
                        tyjmainModel.ownner = tyj.ownner;//个人所有者权限
                                                        //mainModel.note = a.connman + "外部停车收据";这一样留到下面处理
                        tyjmainModel.account = tyj.account;
                        tyjmainModel.accountid = tyj.accountid;//因为数据处理
                        tyjmainModel.accountidb = tyj.accountid;
                        tyjmainModel.accountb = tyj.account;
                        tyjmainModel.shifub = tyj.lanya_money+tyj.menjin_money;//蓝牙和门禁押金加起来
                        tyjmainModel.total = tyjmainModel.shifub;
                        tyjmainModel.payment = tyjmainModel.shifub;
                        tyjmainModel.operate = SysVisitor.Instance.cookiesUserName;
                        tyjmainModel.operateid = int.Parse(SysVisitor.Instance.cookiesUserDepId);
                        #endregion


                        //再写财务主表返回财务主表keyid
                        tyjmainModel.note = tyj.connman + "退押金，外部停车表ID是：" + tyj.KeyId;
                        tyjmainInsertedId = DbUtils.tranInsert(tyjmainModel, tyjtran);


                        #region 财务明细表处理-停车费
                        //先处理费用科目以便以后更新和系统一致 退出入卡押金
                        DataRow fdr = SqlEasy.ExecuteDataRow("select * from MJaccountingSubjects where keyid=22");
                        MJFinanceDetailModel detailModeltcrk = new MJFinanceDetailModel();//初始化明细表模型
                        detailModeltcrk.edNumber = tuiedNumber;//订单号赋值
                        detailModeltcrk.financeId = tyjmainInsertedId;//父子表关联
                        detailModeltcrk.add_time = DateTime.Now;
                        detailModeltcrk.up_time = DateTime.Now;
                        detailModeltcrk.ownner = int.Parse(SysVisitor.Instance.cookiesUserId);//数据所有者ID
                        detailModeltcrk.depid = int.Parse(SysVisitor.Instance.cookiesUserDepId);//数据权限部门ID
                        detailModeltcrk.ftype = "支出";
                        detailModeltcrk.subject = fdr["subjectName"].ToString();
                        detailModeltcrk.subjectid = int.Parse(fdr["keyid"].ToString());
                        detailModeltcrk.num = 1;
                        detailModeltcrk.sprice = tyj.menjin_money;//出入卡押金
                        detailModeltcrk.sumMoney = tyj.menjin_money;
                        detailModeltcrk.stime = tyj.order_starttime;
                        detailModeltcrk.etime = tyj.order_endtime;
                        detailModeltcrk.note = tyj.connman + "停车_退出入卡押金(外部)";
                        detailModeltcrk.username = tyj.connman;
                        detailModeltcrk.mobile = tyj.mobile;
                        detailModeltcrk.contact = SysVisitor.Instance.cookiesUserName;
                        detailModeltcrk.contactid = int.Parse(SysVisitor.Instance.cookiesUserId);

                        #endregion
                        //插入财务信息字表
                        DbUtils.tranInsert(detailModeltcrk, tyjtran);

                        //退蓝牙卡押金




                        #region 财务明细表处理-退蓝牙卡押金
                        //先处理费用科目以便以后更新和系统一致 退出入卡押金
                        DataRow tlydr = SqlEasy.ExecuteDataRow("select * from MJaccountingSubjects where keyid=35");
                        MJFinanceDetailModel detailModeltlyk = new MJFinanceDetailModel();//初始化明细表模型
                        detailModeltlyk.edNumber = tuiedNumber;//订单号赋值
                        detailModeltlyk.financeId = tyjmainInsertedId;//父子表关联
                        detailModeltlyk.add_time = DateTime.Now;
                        detailModeltlyk.up_time = DateTime.Now;
                        detailModeltlyk.ownner = int.Parse(SysVisitor.Instance.cookiesUserId);//数据所有者ID
                        detailModeltlyk.depid = int.Parse(SysVisitor.Instance.cookiesUserDepId);//数据权限部门ID
                        detailModeltlyk.ftype = "支出";
                        detailModeltlyk.subject = tlydr["subjectName"].ToString();
                        detailModeltlyk.subjectid = int.Parse(tlydr["keyid"].ToString());
                        detailModeltlyk.num = 1;
                        detailModeltlyk.sprice = tyj.lanya_money;//退蓝牙卡押金
                        detailModeltlyk.sumMoney = tyj.lanya_money;
                        detailModeltlyk.stime = tyj.order_starttime;
                        detailModeltlyk.etime = tyj.order_endtime;
                        detailModeltlyk.note = tyj.connman + "停车_退蓝牙卡押金(外部)";
                        detailModeltlyk.username = tyj.connman;
                        detailModeltlyk.mobile = tyj.mobile;
                        detailModeltlyk.contact = SysVisitor.Instance.cookiesUserName;
                        detailModeltlyk.contactid = int.Parse(SysVisitor.Instance.cookiesUserId);

                        #endregion
                        //插入财务信息字表
                        DbUtils.tranInsert(detailModeltlyk, tyjtran);




                        //更新零时停车主表
                        string[] upfiles = { "tuiednumber"};
                        DbUtils.tranUpdateOnlyUpdateFields(tyj, tyjtran, upfiles);

                        #region 写成功日志
                        LogModel log = new LogModel();
                        log.BusinessName = "外部停车退押金业务办理成功";
                        log.OperationIp = PublicMethod.GetClientIP();
                        log.OperationTime = DateTime.Now;
                        log.PrimaryKey = "";
                        log.UserId = int.Parse(SysVisitor.Instance.cookiesUserId);
                        log.TableName = "";
                        log.note = "外部停车退押金业务办理成功";
                        log.OperationType = (int)OperationType.Other;
                        LogDal.Instance.Insert(log);
                        #endregion
                        tyjtran.Commit();//提交事务
                        context.Response.Write("{\"status\":1,\"msg\":\"外部停车退押金业务办理成功！\"}");

                    }
                    catch (Exception e)
                    {
                        LogModel log = new LogModel();
                        log.BusinessName = "外部停车退押金失败";
                        log.OperationIp = PublicMethod.GetClientIP();
                        log.OperationTime = DateTime.Now;
                        log.PrimaryKey = "";
                        log.UserId = int.Parse(SysVisitor.Instance.cookiesUserId);
                        log.TableName = "";
                        log.note = e.Message.ToString();
                        log.OperationType = (int)OperationType.Other;
                        LogDal.Instance.Insert(log);


                        tyjtran.Rollback();//错误！事务回滚！
                        context.Response.Write("{\"status\":0,\"msg\":\"" + e.ToString() + "\"}");
                        throw;
                    }




                    break;



                case "xf":
                    int xfmainInsertedId = 0;//（主表公用）主表插入的ID
                    string xfedNumber = common.mjcommon.getedNumber("TX");//得到此次财务订单号，原来是浏览器给，现在从系统获取
                    MJWbtcModel xf = new MJWbtcModel();
                    xf.InjectFrom(rpm.Entity);
                    xf.KeyId = rpm.KeyId;
                    xf.lastedNumber = xfedNumber;//最后一次续费单号
                    xf.lastxftime = DateTime.Now;
   



                    SqlTransaction xftran = SqlHelper.BeginTransaction(SqlEasy.connString);//取得一个事务
                    try
                    {


                        #region 财务主表处理
                        MJFinanceMainModel xfmainModel = new MJFinanceMainModel();//初始化模型
                        xfmainModel.add_time = DateTime.Now;
                        xfmainModel.up_time = DateTime.Now;
                        xfmainModel.edNumber = xfedNumber;
                        xfmainModel.depid = int.Parse(SysVisitor.Instance.cookiesUserDepId);//数据权限部门ID
                        xfmainModel.dep = SysVisitor.Instance.cookiesCurrentDepName;
                        xfmainModel.ownner = int.Parse(SysVisitor.Instance.cookiesUserId);//数据所有者ID
                        xfmainModel.unit = xf.connman;//联系人
                        xfmainModel.unitid = 0;//应为不在用户系统里面故此填写0
                        xfmainModel.contact = SysVisitor.Instance.cookiesUserName;
                        xfmainModel.contactid = int.Parse(SysVisitor.Instance.cookiesUserId);//经手人
                        xfmainModel.depid = xf.depid;//部门权限
                        xfmainModel.ownner = xf.ownner;//个人所有者权限
                                                      //mainModel.note = a.connman + "外部停车收据";这一样留到下面处理
                        xfmainModel.account = xf.account;
                        xfmainModel.accountid = xf.accountid;//因为数据处理
                        xfmainModel.accountidb = xf.accountid;
                        xfmainModel.accountb = xf.account;
                        xfmainModel.shifub = xf.tcf;//三个费用加起来
                        xfmainModel.total = xfmainModel.shifub;
                        xfmainModel.payment = xfmainModel.shifub;
                        xfmainModel.operate = SysVisitor.Instance.cookiesUserName;
                        xfmainModel.operateid = int.Parse(SysVisitor.Instance.cookiesUserDepId);
                        #endregion


                        //再写财务主表返回财务主表keyid
                        xfmainModel.note = xf.connman + "外部停车续费，外部停车表ID是：" + xf.KeyId;
                        xfmainInsertedId = DbUtils.tranInsert(xfmainModel, xftran);


                        #region 财务明细表处理-停车费
                        //先处理费用科目以便以后更新和系统一致
                        DataRow fdr = SqlEasy.ExecuteDataRow("select * from MJaccountingSubjects where keyid=" + xf.subjectid + "");
                        MJFinanceDetailModel detailModeltcf = new MJFinanceDetailModel();//初始化明细表模型
                        detailModeltcf.edNumber = xfedNumber;//订单号赋值
                        detailModeltcf.financeId = xfmainInsertedId;//父子表关联
                        detailModeltcf.add_time = DateTime.Now;
                        detailModeltcf.up_time = DateTime.Now;
                        detailModeltcf.ownner = int.Parse(SysVisitor.Instance.cookiesUserId);//数据所有者ID
                        detailModeltcf.depid = int.Parse(SysVisitor.Instance.cookiesUserDepId);//数据权限部门ID
                        detailModeltcf.ftype = "收入";
                        detailModeltcf.subject = fdr["subjectName"].ToString();
                        detailModeltcf.subjectid = int.Parse(fdr["keyid"].ToString());
                        detailModeltcf.num = 1;
                        detailModeltcf.sprice = xf.tcf;//停车费
                        detailModeltcf.sumMoney = xf.tcf;
                        detailModeltcf.stime = xf.order_starttime;
                        detailModeltcf.etime = xf.order_endtime;
                        detailModeltcf.note = xf.connman + "停车续费(外部)";
                        detailModeltcf.username = xf.connman;
                        detailModeltcf.mobile = xf.mobile;
                        detailModeltcf.contact = SysVisitor.Instance.cookiesUserName;
                        detailModeltcf.contactid = int.Parse(SysVisitor.Instance.cookiesUserId);

                        #endregion
                        //插入财务信息字表
                        DbUtils.tranInsert(detailModeltcf, xftran);


                        

                        //更新零时停车主表
                        string[] upfiles = { "lastednumber", "lastxftime", "up_time", "order_starttime", "order_endtime", "connman", "mobile", "note" };
                        DbUtils.tranUpdateOnlyUpdateFields(xf, xftran, upfiles);

                        #region 写成功日志
                        LogModel log = new LogModel();
                        log.BusinessName = "外部停车续费办理成功";
                        log.OperationIp = PublicMethod.GetClientIP();
                        log.OperationTime = DateTime.Now;
                        log.PrimaryKey = "";
                        log.UserId = int.Parse(SysVisitor.Instance.cookiesUserId);
                        log.TableName = "";
                        log.note = "外部停车续费业务办理成功";
                        log.OperationType = (int)OperationType.Other;
                        LogDal.Instance.Insert(log);
                        #endregion
                        xftran.Commit();//提交事务
                        context.Response.Write("{\"status\":1,\"msg\":\"外部停车续费业务办理成功！\"}");

                    }
                    catch (Exception e)
                    {
                        LogModel log = new LogModel();
                        log.BusinessName = "外部停车续费失败";
                        log.OperationIp = PublicMethod.GetClientIP();
                        log.OperationTime = DateTime.Now;
                        log.PrimaryKey = "";
                        log.UserId = int.Parse(SysVisitor.Instance.cookiesUserId);
                        log.TableName = "";
                        log.note = e.Message.ToString();
                        log.OperationType = (int)OperationType.Other;
                        LogDal.Instance.Insert(log);


                        xftran.Rollback();//错误！事务回滚！
                        context.Response.Write("{\"status\":0,\"msg\":\"" + e.ToString() + "\"}");
                        throw;
                    }
                    break;

                case "edit":
                    MJWbtcModel d = new MJWbtcModel();
                    d.InjectFrom(rpm.Entity);
                    d.KeyId = rpm.KeyId;
                    d.up_time = DateTime.Now;
                    //只更新以下字段
                    string[] upfields = { "carno", "up_time", "order_starttime", "order_endtime", "connman", "mobile", "note" };
                    context.Response.Write(DbUtils.UpdateOnlyUpdateFields(d, upfields));
                    //context.Response.Write(MJWbtcBll.Instance.Update(d));
                    break;
                case "export":
                    //string fields = rpm.fields;
                    string fields = rpm.CurrentContext.Request["fields"];
                    string tablename = TableConvention.Resolve(typeof(MJWbtcModel));//得到表名
                    DataTable xlsDt = SqlEasy.ExecuteDataTable("select " + fields + " from " + tablename + "");
                    ExcelHelper.NPIOtoExcel(xlsDt, HttpContext.Current.Server.MapPath("\\upload\\excel\\" + tablename + ".xls"));
                    context.Response.Write("{\"status\":\"ok\",\"filename\":\"" + tablename + ".xls\"}");
                    break;
                case "inport"://从Excel导入到数据库
                    if (context.Request["REQUEST_METHOD"] == "OPTIONS")
                    {
                        context.Response.End();
                    }
                    SaveFile("~/temp/", context);
                    break;
                case "delete":
                    context.Response.Write(MJWbtcBll.Instance.Delete(rpm.KeyId));
                    break;
                case "alldel"://2017-04-05新增的功能 批量删除删除结果返回删除条数
                    context.Response.Write(NetWing.Dal.MJWbtcDal.Instance.Delete(rpm.KeyIds));
                    break;
                default:

                    string sqlwhere = "(depid in (" + SysVisitor.Instance.cookiesDepartments + "))";
                    if (SysVisitor.Instance.cookiesIsAdmin == "True")
                    { //判断是否是超管如果是超管理，所有显示
                        sqlwhere = " 1=1 ";//如果是超管则不显示
                    }
                    if (!string.IsNullOrEmpty(rpm.Filter))//如果筛选不为空
                    {
                        string str = " and " + FilterTranslator.ToSql(rpm.Filter);
                        sqlwhere = sqlwhere + str;
                    }
                    //TableConvention.Resolve(typeof(MJUserModel)) 转换成表名
                    //默认排序keyid
                    string mysort = null;
                    if (rpm.Sort == null)
                    {
                        mysort = "keyid desc";
                    }
                    else
                    {
                        mysort = rpm.Sort;
                    }

                    var pcp = new ProcCustomPage(TableConvention.Resolve(typeof(MJWbtcModel)))
                    {
                        PageIndex = rpm.Pageindex,
                        PageSize = rpm.Pagesize,
                        OrderFields = mysort,
                        WhereString = sqlwhere
                    };
                    int recordCount;
                    DataTable dt = DbUtils.GetPageWithSp(pcp, out recordCount);
                    context.Response.Write(JSONhelper.FormatJSONForEasyuiDataGrid(recordCount, dt));



                    //context.Response.Write(MJWbtcBll.Instance.GetJson(rpm.Pageindex, rpm.Pagesize, rpm.Filter, rpm.Sort, rpm.Order));
                    break;
            }
        }

        /// <summary>
        /// 文件保存操作
        /// </summary>
        /// <param name="basePath"></param>
        private void SaveFile(string basePath, HttpContext context)
        {
            var name = string.Empty;
            basePath = (basePath.IndexOf("~") > -1) ? context.Server.MapPath(basePath) :
            basePath;
            HttpFileCollection files = context.Request.Files;

            if (!Directory.Exists(basePath))//如果文件夹不存在创建文件夹
                Directory.CreateDirectory(basePath);
            //清空temp文件夹
            DirFileHelper.ClearDirectory(basePath);

            var suffix = files[0].ContentType.Split('/');
            var _suffix = suffix[1].Equals("jpeg", StringComparison.CurrentCultureIgnoreCase) ? "" : suffix[1];
            var _temp = System.Web.HttpContext.Current.Request["name"];

            if (!string.IsNullOrEmpty(_temp))
            {
                name = _temp;
            }
            else
            {
                Random rand = new Random(24 * (int)DateTime.Now.Ticks);
                name = rand.Next() + "." + _suffix;
            }

            var full = basePath + name;
            files[0].SaveAs(full);

            DataTable dt = NPOIHelper.ImportExceltoDt(full);
            string connectionString = SqlEasy.connString;
            SqlBulkCopy sqlbulkcopy = new SqlBulkCopy(connectionString, SqlBulkCopyOptions.UseInternalTransaction);
            sqlbulkcopy.DestinationTableName = TableConvention.Resolve(typeof(MJWbtcModel));//数据库中的表名
                                                                                            //自定义的datatable和数据库的字段进行对应  
                                                                                            //sqlBC.ColumnMappings.Add("id", "tel");  
                                                                                            //sqlBC.ColumnMappings.Add("name", "neirong");  
            int k = dt.Rows.Count - 1;                                                                       //注意一个问题，最后一列是字段数
            for (int i = 0; i < (dt.Columns.Count - 1); i++)
            {
                sqlbulkcopy.ColumnMappings.Add(dt.Columns[i].ColumnName.ToString(), dt.Columns[i].ColumnName.ToString());

            }
            var _result = "";
            try
            {
                sqlbulkcopy.WriteToServer(dt);
                _result = "{\"msg\" : \"导入数据库成功!\", \"result\" : " + k + ", \"filename\" : \"" + name + "\"}";
            }
            catch (Exception)
            {
                _result = "{\"msg\" : \"导入失败,可能模板不对，或其他原因，建议导出数据作为模板重新处理。注意导入没有校验数据重复功能。请人工校验数据!\", \"result\" : 0, \"filename\" : \"" + name + "\"}";
                //throw;
            }



            System.Web.HttpContext.Current.Response.Write(_result);

        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}